<template>
  <div class="warehouseadd">
    <div class="left">
      <el-form :model="warehouseFrom" :rules="rules" ref="warehouseFrom" @click.stop>
        <el-form-item label="城市:" :label-width="formLabelWidth" prop="cityId">
          <el-select
            v-model="warehouseFrom.cityId"
            size="small"
            style="width: 180px;"
            placeholder="请选择城市"
            @visible-change="citydataList"
            @change="getcityIdslist"
          >
            <el-option
              v-for="item in cityList"
              :key="item.id"
              size="small"
              :label="item.deptName"
              :value="{label:item.deptName,value:item.id}"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称:" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model.trim="warehouseFrom.name"
            size="small"
            autocomplete="off"
            style="width: 180px;"
            onafterpaste="value=value.replace(/^[\u0391-\uFFE5A-Za-z]+$/,'').slice(0,20)"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库类型:" :label-width="formLabelWidth" prop="type">
          <el-select
            v-model="warehouseFrom.type"
            size="small"
            style="width: 180px;"
            placeholder="请选择仓库类型"
            @visible-change="getwarehousetype"
            @change="getwarehousetypeId"
          >
            <el-option
              v-for="item in warehousetypeList"
              :key="item.id"
              size="small"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产总仓:" :label-width="formLabelWidth" prop="parentId">
          <el-select
            v-model="warehouseFrom.parentId"
            size="small"
            style="width: 180px;"
            placeholder="请选择生产总仓"
            v-if="warehouseFrom.type==1"
            disabled
          ></el-select>
          <el-select
            v-model="warehouseFrom.parentId"
            size="small"
            style="width: 180px;"
            placeholder="请选择生产总仓"
            @visible-change="getProductionWarehouseByCity"
            @change="getWarehouseIds"
            v-else
          >
            <el-option
              v-for="(item,index) in productionwarehouseList"
              :key="index"
              size="small"
              :label="item.name"
              :value="{label:item.name,value:item.deptId,id:item.id}"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="区域:"
          :label-width="formLabelWidth"
          v-if="warehouseFrom.type==2||warehouseFrom.type==3"
        >
          <el-select
            v-model="deptIdsIdslistName"
            size="small"
            style="width: 180px;"
            placeholder="请选择区域"
            disabled
          ></el-select>
        </el-form-item>
        <el-form-item label="区域:" :label-width="formLabelWidth" prop="deptId" v-else>
          <el-select
            v-model="warehouseFrom.deptId"
            size="small"
            style="width: 180px;"
            placeholder="请选择区域"
            @visible-change="getareadataList"
            @change="getareadataIds"
          >
            <el-option
              v-for="item in areadataList"
              :key="item.id"
              size="small"
              :label="item.deptName"
              :value="{label:item.deptName,value:item.id}"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库地址:" :label-width="formLabelWidth" prop="address">
          <el-input
            id="getDetail"
            v-model.trim="warehouseFrom.address"
            clearable
            size="small"
            autocomplete="off"
            style="width: 180px;"
            @input.native="SearchAddress"
          ></el-input>
        </el-form-item>
        <el-form-item label="下单提前时间:" :label-width="formLabelWidth">
          <el-input
            v-model="warehouseFrom.orderAdvanceTime"
            size="small"
            min="0"
            style="width: 180px;"
            type="number"
          ></el-input>分钟
        </el-form-item>
        <el-form-item label="开始配送时间:" :label-width="formLabelWidth" prop="deliveryStartTime">
          <el-time-select
            v-model="deliveryStartTime"
            :picker-options="{
              start: '08:00',
              step: '01:00',
              end: '24:00'
            }"
            placeholder="选择开始配送时间"
          ></el-time-select>
        </el-form-item>
        <el-form-item label="结束配送时间:" :label-width="formLabelWidth" prop="deliveryEndTime">
          <el-time-select
            v-model="deliveryEndTime"
            :picker-options="{
              start: '08:00',
              step: '01:00',
              end: '24:00'
            }"
            placeholder="选择结束配送时间"
          ></el-time-select>
        </el-form-item>
        <el-form-item label="销售组织ID:" :label-width="formLabelWidth" prop="salesOrganizationId">
          <el-input
            v-model.trim="warehouseFrom.salesOrganizationId"
            size="small"
            type="textarea"
            maxlength="64"
            show-word-limit
            autocomplete="off"
            style="width: 180px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="销售组织名称:" :label-width="formLabelWidth" prop="salesOrganizationName">
          <el-input
            v-model.trim="warehouseFrom.salesOrganizationName"
            size="small"
            autocomplete="off"
            style="width: 180px;"
            type="textarea"
            maxlength="64"
            show-word-limit
          ></el-input>
        </el-form-item>
        <div class="tipsbutton">
          <el-button
            type="primary"
            plain
            size="small"
            @click="Selectwarehouse"
            v-if="warehouseFrom.type==1||warehouseFrom.type==2"
          >添加仓库范围</el-button>
          <el-button
            type="success"
            size="small"
            @click="handlecommit('warehouseFrom',warehouseFrom)"
          >提交</el-button>
        </div>
      </el-form>
      <div class="adressDetailDiv" v-show="adressDetailDivshow">
        <ul v-if="addressFlag&&addressList&&addressList.length" class="adressDetail">
          <li
            v-for="(addressitem,index) in addressList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            :key="index"
            :data-name="addressitem.name"
            :data-lng="addressitem.location.lng"
            :data-lat="addressitem.location.lat"
            @click="getlnglat($event)"
            @mouseover="changeColor($event)"
            @mouseout="loseColor($event)"
          >
            <p class="el-icon-location-information">{{ addressitem.name }}</p>
            <p class="el-icon-location-information">
              地址：
              <span v-if="addressitem.address.length > 0? true : false">{{ addressitem.address }}</span>
            </p>
          </li>
        </ul>
        <div class="close" v-if="addressFlag&&addressList&&addressList.length">
          <i class="el-icon-error Delgoodlist" @click="headleclose"></i>
        </div>
        <el-pagination
          v-if="addressFlag&&addressList&&addressList.length"
          background
          :current-page.sync="currentPage"
          layout="prev, pager, next"
          :page-sizes="[5, 10, 15, 20]"
          :page-size.sync="pagesize"
          :total="addressList.length"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          style="margin-top: 5px 0;"
        ></el-pagination>
      </div>
    </div>
    <div class="right">
      <div class="amap-page-container">
        <!-- :events.stop="events" -->
        <el-amap
          vid="amap-demo"
          :zoom="zoom"
          :amap-manager="amapManager"
          :center="center"
          ref="map"
          class="amap-demo"
        >
          <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker"></el-amap-marker>
          <el-amap-polygon
            v-for="(polygon, index) in polygons"
            :key="index"
            :ref="`polygon_${index}`"
            :path="polygon.path"
            :draggable="polygon.draggable"
          ></el-amap-polygon>
        </el-amap>
        <!-- 电子围栏 -->
        <el-row style="text-align: right;padding:10px" v-if="SelectwarehouseOther">
          <el-button
            type="danger"
            plain
            size="small"
            @click="removeFence"
            v-if="warehouseFrom.type==1||warehouseFrom.type==2"
          >删除仓库地图</el-button>
          <el-button
            type="warning"
            plain
            size="small"
            @click="EditFence"
            v-if="warehouseFrom.type==1||warehouseFrom.type==2"
          >编辑仓库地图</el-button>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getMainWarehouseList,
  selectDeptByCityId,
  deptdepts,
  warehouseSave,
  warehousetype,
  ProductionWarehouseByCity,
} from "@/api/warehouse";
import VueAMap from "vue-amap";
let amapManager = new VueAMap.AMapManager();
var selectversionData;

export default {
  data: function () {
    let self = this;
    return {
      // areaname: this.$store.state.user.areaname || 杭州市,
      warehouseFrom: {
        cityId: "", //城市ID
        deptId: "", //区域ID
        name: "", //仓库名称
        address: "", //仓库编辑地址
        parentId: "", //默认0
        polygon: "", //仓库范围
        status: 1, //默认
        type: "", //默认
        longitude: "", //经度
        latitude: "", // 纬度
        deliveryStartTime: "", //配送开始时间
        deliveryEndTime: "", //配送结束时间
        orderAdvanceTime: "", //下单提前时间(分钟)
        salesOrganizationId: "", //销售组织ID
        salesOrganizationName: "", //销售组织名称
        isUp: 2,
        isAutoReceive: 0,
        closeStartTime: "",
        closeEndTime: "",
      },
      deliveryStartTime: "", //配送开始时间
      deliveryEndTime: "", //配送结束时间
      cityIdslist: "",
      cityIdslistname: "",
      deptIdsIdslist: "",
      adressDetailDivshow: false,
      rules: {
        name: [
          {
            required: true,
            message: "仓库名称不能为空",
            trigger: "blur",
          },
          {
            pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
            message: "仓库名称必须包含中英文",
            trigger: "blur",
          },
        ],
        cityId: [
          {
            required: true,
            message: "请选择城市",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择仓库类型",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择区域",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入仓库地址",
            trigger: "blur",
          },
        ],
        orderAdvanceTime: [
          {
            required: true,
            message: "请输入下单提前时间",
            trigger: "blur",
          },
          {
            type: "number",
            pattern: /[^\d]|^[0]/g,
            message: "下单提前时间只能输入数字",
            trigger: "blur",
            max: 6,
          },
        ],
      },
      formLabelWidth: "120px",
      cityList: [],
      deptIdsIdslist: [],
      areadataList: [],
      // 地图
      zoom: 12,
      center: [121.59996, 31.197646],
      markers: [],
      circles: [
        {
          center: [121.5273285, 31.21515044],
          radius: 200,
          fillOpacity: 0.5,
        },
      ],
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.warehouseFrom.longitude = lng;
          self.warehouseFrom.latitude = lat;
          // console.log(e.lnglat)
          // var map = new AMap.Map("amap-demo", {
          //   resizeEnable: true
          // });
          // var marker = new AMap.Marker();;
          // map.add(marker);
          // marker.setPosition(lng, lat);

          // map.setZoomAndCenter(13, [self.warehouseFrom.longitude, self.warehouseFrom.latitude]);
          // 这里通过高德 SDK 完成。
          AMap.plugin("AMap.Geocoder", function () {
            var geocoder = new AMap.Geocoder({
              city: "010", //城市设为北京，默认：“全国”
              radius: 1000, //范围，默认：500
            });
            // 绑定事件移动地图事件
            geocoder.getAddress([lng, lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.warehouseFrom.address =
                    result.regeocode.formattedAddress;
                  // self.warehouseFrom.longitude = result.regeocode.addressComponent.businessAreas[0].lng;
                  // self.warehouseFrom.latitude = result.regeocode.addressComponent.businessAreas[0].lat;
                  self.$nextTick();
                }
              }
            });
          });
        },
      },
      fenceForm: {
        coordinate: [],
      },
      rectangle: null,
      mouseTool: null,
      overlays: [],
      // lng: 0,
      // lat: 0,
      gMap2: "",
      amapManager: amapManager,
      polygons: [
        {
          draggable: true,
          path: [],
          events: {
            click: () => {
              var polyEditor = new AMap.PolyEditor(map, polygon);
              var polygon = new AMap.Polygon({
                path: path,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                fillColor: "#1791fc",
                zIndex: 50,
              });

              this.currentDrawPolygon.setMap(null);
              this.currentDrawPolygon = this.createPolygon([
                ...this.path,
                this.mousePoint,
              ]);
              this.currentDrawPolygon.setMap(polygon);
            },
          },
        },
      ],
      wareData: [],
      addressFlag: false,
      addressList: [], // 地址详情列表
      pagesize: 5,
      currentPage: 1,
      newcenter: "",
      SelectwarehouseOther: false,
      cityareaName: "",
      warehousetypeList: [], //仓库类型
      productionwarehouseList: [], //生产总仓
      deptIdsIdslistName: "", //配送分仓禁用
    };
  },
  mounted() {
    var saberareaName = JSON.parse(localStorage.getItem("saber-areaname"));
    this.cityareaName = saberareaName["content"];
    this.getMapaddress(this.cityareaName);
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    getmap() {
      this.mapObj = new AMap.Map("amap-demo", {
        resizeEnable: true,
        zoom: 10,
      });
    },
    headleclose() {
      this.adressDetailDivshow = false;
      this.warehouseFrom.address = "";
    },
    //根据城市获取地图位置
    getMapaddress(name) {
      var MSearch;
      var mapObj = new AMap.Map("amap-demo", {
        resizeEnable: true,
        center: [116.397428, 39.90923], //地图中心点
        zoom: 10, //地图显示的缩放级别
      });
      mapObj.plugin(["AMap.PlaceSearch"], () => {
        // mapObj.addControl(new AMap.ToolBar())
        // mapObj.addControl(new AMap.Scale())
        MSearch = new AMap.PlaceSearch({
          //构造地点查询类
          city: "北京市", //城市
        });
        AMap.event.addListener(
          MSearch,
          "complete",
          this.keywordSearch_CallBack
        ); //返回地点查询结果
        MSearch.search(name); //关键字查询
      });
    },
    keywordSearch_CallBack(data) {
      var mapObj = new AMap.Map("amap-demo", {
        resizeEnable: true,
      });
      var poiArr = data.poiList.pois;
      var resultCount = poiArr.length;
      this.poiArr = poiArr; //左边要渲染的数据
      mapObj.setFitView();
      mapObj.setZoomAndCenter(14, [
        poiArr[0].location.lng,
        poiArr[0].location.lat,
      ]);
      this.newcenter = [poiArr[0].location.lng, poiArr[0].location.lat];
    },

    citydataList() {
      //获取城市列表数据
      deptdepts("").then((response) => {
        this.cityList = response.data.data;
      });
    },
    //仓库类型
    getwarehousetype() {
      warehousetype("").then((response) => {
        this.warehousetypeList = response.data.data;
      });
    },
    //生产总仓
    getProductionWarehouseByCity() {
      if (this.cityIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
      } else {
        ProductionWarehouseByCity({ cityId: this.cityIdslist }).then(
          (response) => {
            this.productionwarehouseList = response.data.data;
          }
        );
      }
    },

    getcityIdslist(data) {
      //获取城市列表ID
      this.cityIdslist = data.value;
      this.cityIdslistname = data.label;
      this.warehouseFrom.name = "";
      this.warehouseFrom.address = "";
      this.warehouseFrom.parentId = "";
      this.warehouseFrom.type = "";
      this.warehouseFrom.deptId = "";
      this.deliveryStartTime = "";
      this.deliveryEndTime = ""; //配送结束时间
      this.warehouseFrom.orderAdvanceTime = ""; //下单提前时间(分钟)
      this.warehouseFrom.salesOrganizationId = ""; //销售组织ID
      this.warehouseFrom.salesOrganizationName = ""; //销售组织名称
      this.fenceForm.coordinate = [];
      console.log(this.$refs.map, "this.$refs.map");
      this.$refs.map.$amap.clearMap();
      selectversionData = [];
      var mapObj = new AMap.Map("container", {
        resizeEnable: true,
        // center: this.newcenter,
      });
      this.polygonEdit = "";
      this.geoJson = "";
      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
      if (this.polygon) {
        amapManager.getMap().remove(this.polygon);
      }
    },
    getwarehousetypeId(data) {
      this.warehouseFrom.type = data;
      // this.parentId = "";
      this.warehouseFrom.deptId = "";
      this.deptIdsIdslist = "";
      this.deptIdsIdslistName = "";
      this.warehouseFrom.parentId = "";
      this.warehouseFrom.deptId = "";
      if (data == "1") {
        this.deptIdsIdslistName = "";
        // this.getArea(this.warehouseFrom);
      } else if (data == "3") {
        console.log("123");
        this.fenceForm.coordinate = [];
        selectversionData = [];
        var mapObj = new AMap.Map("container", {
          resizeEnable: true,
          // center: this.newcenter,
        });
        this.polygonEdit = "";
        this.geoJson = "";
        if (this.mouseTool) {
          this.mouseTool.close(true);
        }
        if (this.polygon) {
          amapManager.getMap().remove(this.polygon);
        }
      } else if (data == "2") {
        // this.getArea(this.warehouseFrom);
      }
    },
    getWarehouseIds(data) {
      this.parentId = data.id;
      selectDeptByCityId({
        cityId: this.cityIdslist,
      }).then((res) => {
        this.areadataList = res.data.data;
        this.areadataList.forEach((item) => {
          if (data.value == item.id) {
            this.deptIdsIdslist = item.id;
            this.deptIdsIdslistName = item.deptName;
          }
        });
      });
    },
    getareadataIds(data) {
      //获取区域列表ID
      this.deptIdsIdslist = data.value;
    },
    // 点击列表获取经纬度
    getlnglat(e) {
      var map = new AMap.Map("amap-demo");
      let _this = this;
      this.addressFlag = false;
      let pois = e.currentTarget.dataset;
      this.warehouseFrom.latitude = pois.lat;
      this.warehouseFrom.longitude = pois.lng;
      this.warehouseFrom.address = pois.name;
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(pois.lng, pois.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      });
      map.add(this.marker);
      // 绑定事件移动地图事件
      map.setZoomAndCenter(13, [pois.lng, pois.lat]);
    },
    changeColor(e) {
      e.currentTarget.style.background = "#F5F7FA";
    },
    // 离开列表颜色改变
    loseColor(e) {
      e.currentTarget.style.background = "#fff";
    },
    getareadataList() {
      //区域下拉
      if (this.cityIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
      } else {
        selectDeptByCityId({
          cityId: this.cityIdslist,
        }).then((res) => {
          this.areadataList = res.data.data;
        });
      }
    },

    handlecommit(warehouseFrom, item) {
      console.log(item, "item");
      this.$refs[warehouseFrom].validate((valid) => {
        if (valid) {
          if (item.orderAdvanceTime <= 0) {
            this.$message({
              showClose: true,
              message: "下单提前时间需要大于0 ",
              type: "warning",
            });
            return false;
          } else if (item.orderAdvanceTime > 86400) {
            this.$message({
              showClose: true,
              message: "下单提前时间不可大于86400 ",
              type: "warning",
            });
            return false;
          } else if (
            this.deliveryStartTime == "" ||
            this.deliveryStartTime == null
          ) {
            this.$message({
              showClose: true,
              message: "配送开始时间不能为空 ",
              type: "warning",
            });
            return false;
          } else if (
            this.deliveryEndTime == "" ||
            this.deliveryEndTime == null
          ) {
            this.$message({
              showClose: true,
              message: "配送结束时间不能为空 ",
              type: "warning",
            });
            return false;
          } else if (this.deliveryEndTime <= this.deliveryStartTime) {
            this.$message({
              showClose: true,
              message: "结束时间要大于开始时间 ",
              type: "warning",
            });
            return false;
          } else if (item.polygonBy == "") {
            this.$message({
              showClose: true,
              message: "请勾画仓库范围",
              type: "warning",
            });
            return false;
          } else if (
            (item.type == "2" && this.parentId == "") ||
            (item.type == "3" && this.parentId == "")
          ) {
            this.$message({
              showClose: true,
              message: "该仓库类型的生产总仓不能为空！",
              type: "warning",
            });
            return false;
          } else if (item.type == "3") {
            this.$confirm("选择自提仓, 是没有配送范围的,确定保存?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                const warehouse = {
                  cityId: this.cityIdslist, //城市ID
                  deptId: this.deptIdsIdslist, //区域ID
                  name: item.name, //仓库名称
                  address: item.address, //仓库编辑地址
                  parentId: item.type == "1" ? 0 : this.parentId, //生产总仓id（只有选择类型为配送分仓和自提分仓传选中的生产总仓id,其它类型传0）
                  polygonBy:
                    item.type == 3 ? "" : this.fenceForm.coordinate.join(";"), //仓库范围
                  status: 1, //默认
                  type: item.type, //类型：1:生产总仓；2:配送分仓 ; 3.自提分仓
                  longitude: item.longitude, //经度
                  latitude: item.latitude, // 纬度
                  deliveryStartTime: this.deliveryStartTime + ":00", //配送开始时间
                  deliveryEndTime: this.deliveryEndTime + ":00", //配送结束时间
                  orderAdvanceTime: item.orderAdvanceTime, //下单提前时间(分钟)
                  salesOrganizationId: item.salesOrganizationId,
                  salesOrganizationName: item.salesOrganizationName,
                  isUp: 2,
                  isAutoReceive: 0,
                  closeStartTime: item.closeStartTime,
                  closeEndTime: item.closeEndTime,
                };

                if (warehouse.deliveryEndTime <= warehouse.deliveryStartTime) {
                  this.$message({
                    showClose: true,
                    message: "结束时间要大于开始时间 ",
                    type: "warning",
                  });
                  return false;
                } else {
                  warehouseSave(warehouse).then((res) => {
                    this.$message({
                      type: "success",
                      message: "操作成功!",
                    });
                    // setTimeout(() => {
                    //   this.listLoading = false;
                    // }, 1.5 * 1000);
                    // if (warehouseFrom) {
                    //   this.$refs[warehouseFrom].resetFields();
                    // }
                    this.cityIdslist = "";
                    this.deliveryStartTime = "";
                    this.deliveryEndTime = "";
                    this.fenceForm.coordinate = [];
                    selectversionData = [];
                    this.polygons = [];
                    var mapObj = new AMap.Map("amap-demo", {
                      resizeEnable: true,
                    });
                    mapObj.setFitView();
                    this.$emit("close");
                    this.$emit("getList", this.warehouseData);
                    window.location.reload();
                  });
                }
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
          } else {
            const warehouse = {
              cityId: this.cityIdslist, //城市ID
              deptId: this.deptIdsIdslist, //区域ID
              name: item.name, //仓库名称
              address: item.address, //仓库编辑地址
              parentId: item.type == "1" ? 0 : this.parentId, //生产总仓id（只有选择类型为配送分仓和自提分仓传选中的生产总仓id,其它类型传0）
              polygonBy:
                item.type == 3 ? "" : this.fenceForm.coordinate.join(";"), //仓库范围
              status: 1, //默认
              type: item.type, //类型：1:生产总仓；2:配送分仓 ; 3.自提分仓
              longitude: item.longitude, //经度
              latitude: item.latitude, // 纬度
              deliveryStartTime: this.deliveryStartTime + ":00", //配送开始时间
              deliveryEndTime: this.deliveryEndTime + ":00", //配送结束时间
              orderAdvanceTime: item.orderAdvanceTime, //下单提前时间(分钟)
              salesOrganizationId: item.salesOrganizationId,
              salesOrganizationName: item.salesOrganizationName,
              isUp: 2,
              isAutoReceive: 0,
              closeStartTime: item.closeStartTime,
              closeEndTime: item.closeEndTime,
            };

            if (warehouse.deliveryEndTime <= warehouse.deliveryStartTime) {
              this.$message({
                showClose: true,
                message: "结束时间要大于开始时间 ",
                type: "warning",
              });
              return false;
            } else {
              warehouseSave(warehouse).then((res) => {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                // setTimeout(() => {
                //   this.listLoading = false;
                // }, 1.5 * 1000);
                // if(warehouseFrom){
                //   this.$refs[warehouseFrom].resetFields();
                // }

                this.cityIdslist = "";
                this.deliveryStartTime = "";
                this.deliveryEndTime = "";
                this.fenceForm.coordinate = [];
                selectversionData = [];
                this.polygons = [];
                var mapObj = new AMap.Map("amap-demo", {
                  resizeEnable: true,
                });
                mapObj.setFitView();
                this.$emit("close");
                this.$emit("getList", this.warehouseData);
                window.location.reload();
              });
            }
          }
        } else {
          this.$message({
            message: "信息未填完整",
            type: "warning",
          });
          return false;
        }
      });
    },
    SearchAddress() {
      if (this.cityIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else if (this.deptIdsIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择区域",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else {
        this.addressFlag = true;
        let _this = this;
        var keywords = document.getElementById("getDetail").value;
        AMap.plugin("AMap.Autocomplete", function () {
          // 实例化Autocomplete
          var autoOptions = {
            city: "全国",
          };
          var autoComplete = new AMap.Autocomplete(autoOptions);
          autoComplete.search(keywords, function (status, result) {
            // 搜索成功时，result即是对应的匹配数据
            if (result.tips !== undefined) {
              _this.addressList = result.tips;
              if (_this.addressList && _this.addressList.length > 0) {
                _this.adressDetailDivshow = true;
              } else {
                _this.$message("搜索无结果请重新输入");
                _this.adressDetailDivshow = false;
              }
            } else {
              _this.$message({
                showClose: true,
                message: "搜索无结果请重新输入",
                type: "warning",
              });
            }
          });
        });
      }
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange(size) {
      this.pagesize = size;
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },

    Selectwarehouse() {
      // 选择仓库范围添加自定义多边形
      this.SelectwarehouseOther = true;

      if (this.cityIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
        return false;
      } else if (this.deptIdsIdslist == "") {
        this.$message({
          showClose: true,
          message: "请选择区域",
          type: "warning",
        });
        return false;
      } else if (this.warehouseFrom.address == "") {
        this.$message({
          showClose: true,
          message: "请选择仓库地址",
          type: "warning",
        });
        return false;
      } else {
        let _this = this;
        var mapObj = new AMap.Map("amap-demo", {
          resizeEnable: true,
        });
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(
            this.warehouseFrom.longitude,
            this.warehouseFrom.latitude
          ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        });
        mapObj.add(this.marker);
        mapObj.setZoomAndCenter(13, [
          this.warehouseFrom.longitude,
          this.warehouseFrom.latitude,
        ]);
        mapObj.plugin(["AMap.MouseTool"], function () {
          let mouseTool = new AMap.MouseTool(mapObj);
          _this.mouseTool = mouseTool;
          //添加事件
          mouseTool.polygon();
          mouseTool.polygon({
            strokeColor: "#FF33FF",
            strokeOpacity: 1,
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillColor: "#1791fc",
            fillOpacity: 0.4,
            strokeStyle: "solid",
            // strokeStyle是dashed时有效
            // strokeDasharray: [30,10],
          });
          AMap.event.addListener(mouseTool, "draw", function (e) {
            _this.fenceForm.coordinate = [];
            let path = e.obj.getPath();
            path.forEach((e) => {
              _this.fenceForm.coordinate.push([e.getLng(), e.getLat()]);
            });
            selectversionData = _this.fenceForm.coordinate.map((item) => item);
          });
        });
      }
    },
    removeFence() {
      this.fenceForm.coordinate = [];
      selectversionData = [];
      var mapObj = new AMap.Map("amap-demo", {
        resizeEnable: true,
        // center: this.newcenter,
      });
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(
          this.warehouseFrom.longitude,
          this.warehouseFrom.latitude
        ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      });
      mapObj.add(this.marker);
      mapObj.setZoomAndCenter(13, [
        this.warehouseFrom.longitude,
        this.warehouseFrom.latitude,
      ]);

      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
      if (this.polygon) {
        amapManager.getMap().remove(this.polygon);
      }
      this.SelectwarehouseOther = false;
    },
    EditFence() {
      var _this = this;
      var mapObj = new AMap.Map("amap-demo", {
        resizeEnable: true,
        // center: this.newcenter,
      });
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(
          this.warehouseFrom.longitude,
          this.warehouseFrom.latitude
        ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      });
      mapObj.add(this.marker);

      //定义折线对象
      var polygon = new AMap.Polygon({
        path: selectversionData,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: "#1791fc",
        zIndex: 50,
      });
      mapObj.add(polygon);
      // 缩放地图到合适的视野级别
      mapObj.setFitView([polygon]);
      // polygon.setMap(mapObj); //地图上添加折线

      //构造折线编辑对象，并开启折线的编辑状态
      mapObj.plugin(["AMap.PolyEditor"], function () {
        var polyEditor = new AMap.PolyEditor(mapObj, polygon);
        _this.fenceForm.coordinate = polygon.getPath();
        polyEditor.open();
      });
    },

    // OverFence() {
    //   var mapObj = new AMap.Map("amap-demo", {
    //     resizeEnable: true
    //   });
    //   //定义折线对象
    //   var polygon = new AMap.Polygon({
    //     path: selectversionData,
    //     strokeColor: "#FF33FF",
    //     strokeWeight: 6,
    //     strokeOpacity: 0.2,
    //     fillOpacity: 0.4,
    //     fillColor: "#1791fc",
    //     zIndex: 50
    //   });
    //   mapObj.add(polygon);
    //   // 缩放地图到合适的视野级别
    //   mapObj.setFitView([polygon]);
    //   //构造多边形编辑对象，并多边形的编辑状态
    //   mapObj.plugin(["AMap.PolyEditor"], function() {
    //     var polyEditor = new AMap.PolyEditor(mapObj, polygon);
    //     polyEditor.close();
    //   });
    // }
  },
};
</script>

<style lang="scss">
.warehouseadd {
  display: flex;
  justify-content: space-between;

  .left {
    .el-form-item {
      margin-bottom: 22px !important;
    }

    width: 35%;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    overflow: hidden;
    color: #606266;
    transition: 0.3s;
    margin-bottom: 10px;

    position: relative;

    .tipsbutton {
      text-align: right;
    }

    .adressDetailDiv {
      background: #fff;
      position: absolute;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      top: 48%;
      z-index: 99;
      box-sizing: border-box;
      width: 350px;
      left: 15%;

      .adressDetail {
        margin: 0;
        padding: 0;
        list-style: none;
        border: 1px solid #dcdfe6;
        margin-bottom: 5px;

        li {
          border-bottom: 1px solid #dcdfe6;

          p {
            margin: 0;
            padding: 0 10px;
            list-style: none;
            width: 280px;
            text-align: left;
            line-height: 1.6;

            &:first-child {
              font-size: 17px;
            }

            &:last-child {
              color: #999;
            }
          }
        }
      }

      .close {
        position: absolute;
        right: 2px;
        top: 2px;
      }
    }
  }

  .right {
    width: 60%;

    .amap-demo {
      width: 100%;
      height: 700px;
    }
  }
}
</style>
